interface CacheOptions {
  expire?: number // 过期时间（毫秒）
}

class Cache {
  private storage: Storage

  constructor(useSession = false) {
    this.storage = useSession ? sessionStorage : localStorage
  }

  set(key: string, value: any, options: CacheOptions = {}) {
    const data = {
      value,
      expire: options.expire ? Date.now() + options.expire : null
    }
    this.storage.setItem(key, JSON.stringify(data))
  }

  get(key: string) {
    const item = this.storage.getItem(key)
    if (!item) return null

    const data = JSON.parse(item)
    if (data.expire && Date.now() > data.expire) {
      this.remove(key)
      return null
    }
    return data.value
  }

  remove(key: string) {
    this.storage.removeItem(key)
  }

  clear() {
    this.storage.clear()
  }
}

export const localCache = new Cache()
export const sessionCache = new Cache(true) 